package cn.itlaobing.web.servlet;

import cn.itlaobing.entity.MsgToken;
import cn.itlaobing.utils.StringUtil;
import cn.itlaobing.web.annotation.MappingAnnotation;
import com.alibaba.fastjson.JSON;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;

/**
 * 类名: cn.itlaobing.web.servlet
 * 功能: 用户的操作
 * 作者:
 * 日期: 2017/11/15 11:21
 */
@WebServlet("/user/*")
public class UserServlet extends BaseServlet {

    /*
        获取短信验证码
     */
    @MappingAnnotation("/chait")
    public void chait(HttpServletRequest request, HttpServletResponse response) throws IOException {
        //获取手机号码
        String phone=request.getParameter("username");
        //获取短信信息
        MsgToken msgToken= (MsgToken) request.getSession().getAttribute("MSGTOKEN");
        //有短信
        if(msgToken!=null){
            //获取上次的时间戳
            //TODO 获取值没有进行验证 上次发送验证码的时间
            long time=msgToken.getCrateAt();
            //判断是不是小于5分钟，小于则不重新发送
            if(System.currentTimeMillis()-time<(300*1000)){
                Map<String,Object> objectMap=new HashMap<String,Object>();
                objectMap.put("success",false);
                objectMap.put("msg","短信验证码已经发送");
                response.setContentType("application/json;charset=utf-8");
                response.getWriter().write(JSON.toJSONString(objectMap));
                return ;
            }
        }
        //无短信
        msgToken=new MsgToken();
        msgToken.setCrateAt(System.currentTimeMillis());
        msgToken.setPhone(phone);
        msgToken.setMsgCode(produceCode());
        Map<String,Object> objectMap=new HashMap<String,Object>();
        objectMap.put("success",true);
        objectMap.put("msg","短信验证码发送成功");
        request.getSession().setAttribute("MSGTOKEN",msgToken);
        response.setContentType("application/json;charset=utf-8");
        response.getWriter().write(JSON.toJSONString(objectMap));
    }

    /*
        产生短信验证码
     */
    private String produceCode(){
        Random random=new Random();
        StringBuffer sb=new StringBuffer();
        for(int i=0;i<6;i++){
            sb.append(random.nextInt(10));
        }
        System.out.println("短信验证码------"+sb.toString());
        return sb.toString();
    }

    /*
        注册用户
     */
    @MappingAnnotation("/register")
    public void register(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        //这里是得到相应的验证码
        String kaptchaExpected = (String)request.getSession()
                .getAttribute(com.google.code.kaptcha.Constants.KAPTCHA_SESSION_KEY);
        String phone=request.getParameter("username");//手机号码
        String pwd=request.getParameter("password");//密码
        String affirmPwd=request.getParameter("rqpwd");//确认密码
        String imgCode=request.getParameter("imgCode");//图片验证码
        String phoneCode=request.getParameter("phonetest");//手机验证码

        //验证手机号是否正确
        if(provingPhone(phone) || provingpwd(pwd) ||
                provingpwd(affirmPwd) || provingImg(imgCode,kaptchaExpected)
                ){
            request.setAttribute("ERRORMESSAGE","信息输入有误");
            skipURL(request,response);
            return;
        }
        if(!pwd.equals(affirmPwd)){
            request.setAttribute("ERRORMESSAGE","信息输入有误");
            skipURL(request,response);
            return;
        }
    }

    /*
     *   跳转到注册页面
     */
    @MappingAnnotation("/skipURL")
    public void skipURL(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.getRequestDispatcher("/WEB-INF/views/display/register.jsp").forward(request,response);
    }

    /*
     * 验证手机验证码是否正确
     */
    private boolean provingPhoneCode(String imgCode,HttpServletRequest request){
        if(StringUtil.isTrimAndNUll(imgCode) && imgCode.length()==4){
            return true;
        }
        MsgToken msgToken= (MsgToken) request.getSession().getAttribute("MSGTOKEN");
        //验证短信时效
        long beforeTime=System.currentTimeMillis();
        if(beforeTime-msgToken.getCrateAt()>300*1000){
            return true;
        }
        if(!imgCode.equals(msgToken.getMsgCode())){
            return true;
        }
        return false;
    }

    /*
     * 验证图片验证码
     */
    private boolean provingImg(String imgCode,String kaptchaExpected){
        if(StringUtil.isTrimAndNUll(imgCode) && imgCode.length()==4){
            return true;
        }
        if(!imgCode.equals(kaptchaExpected)){
            return true;
        }
        return false;
    }

    /*
     * 验证手机号码是否正确
     */
    private boolean provingPhone(String value){
        if(StringUtil.isTrimAndNUll(value)){
            return true;
        }
        String reg="^((13[0-9])|(14[5|7])|(15([0-3]|[5-9]))|(18[0,5-9]))\\d{8}$";
        if(!value.matches(reg)){
            return true;
        }
        return false;
    }

    /*
     * 验证密码
     */
    private boolean provingpwd(String pwd){
        if(StringUtil.isTrimAndNUll(pwd)){
            return true;
        }
        return pwd.length()<6?true:false;
    }


}
